package test;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

import org.junit.Test;

public class ConnectDB {
	
	@Test
	public void testConnect() throws ClassNotFoundException, SQLException {
		// 1.加载驱动class到内存  // mysql5: com.mysql.jdbc.Driver
		Class.forName("com.mysql.cj.jdbc.Driver");
		// 2.驱动管理器直接连接
		//           连接方式:数据库:主机名:端口/库名;
//		String url = "jdbc:mysql://localhost:3306/a_db";   // mysql5的url就OK了
		String url = "jdbc:mysql://localhost:3306/a_db?characterEncoding=utf8&useSSL=false&serverTimezone=CST&allowPublicKeyRetrieval=true";
		String username = "root";
		String password = "123456";
		Connection c = DriverManager.getConnection(url,username,password);
		
		System.out.println(c);
	}
	
	@Test
	public void testConnect2() throws ClassNotFoundException, SQLException, IOException {
		// 1.创建属性类
		Properties pro = new Properties();
		// 2.加载属性文件(需要把属性文件拷贝到src下)
		pro.load(this.getClass().getClassLoader().getResourceAsStream("./jdbc.properties"));
		// 3.获取4个属性值
		String driver = pro.getProperty("jdbc.driver");
		String url = pro.getProperty("jdbc.url");
		String username = pro.getProperty("jdbc.username");
		String password = pro.getProperty("jdbc.password");
		
		// 4.加载驱动
		Class.forName(driver);
		// 5.得到连接
		Connection c = DriverManager.getConnection(url,username,password);
		
		System.out.println(c);
	}
	
	
}
